package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().
                eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 订单结算
     * @return
     */
    @Override
    public TradeVo orderTradeData() {
        TradeVo tradeVo = new TradeVo();
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL == cartCheckedList.getCode()) {
            throw new ServiceException(cartCheckedList.getMsg());
        }
        List<CartInfo> cartInfos = cartCheckedList.getData();
        //结算商品列表
        List<OrderItem> orderItemList= new ArrayList<>();
        if (CollectionUtils.isEmpty(cartInfos)) {
            throw new ServiceException("购物车无选中商品");
        }
        for (CartInfo cartInfo : cartInfos) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo,orderItem);
            orderItemList.add(orderItem);
        }
        //结算总金额
        BigDecimal totalDecaimal = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalDecaimal=totalDecaimal.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        //交易号
        String tradeNo=getTradeNo(userId);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalDecaimal);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }
    private String getTradeNo(Long userId) {
        String tradeKey="user:trade:"+userId;
        String tradeNo= UUID.randomUUID().toString().replaceAll("-","");
        //订单流水号保存在redis中，5分钟过期，可用于去重
        redisTemplate.opsForValue().set(tradeKey,tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 订单提交
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //验证用户重复提交表单
        Long userId = SecurityContextHolder.getUserId();
        String tradeNoFromForm = orderForm.getTradeNo();
        String tradeNoKey="user:trade:"+userId;
        String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "   return redis.call('del',KEYS[1])\n" +
                "else\n" +
                "   return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = (Long) redisTemplate.execute(redisScript, Arrays.asList(tradeNoKey), tradeNoFromForm);
        if (result==0) {
            throw new ServiceException("不能重复提交表单");
        }
        //验证表单参数是否为空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)) {
            throw new ServiceException("数据不能为空");
        }
        //校验价格变化
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceList = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL==skuPriceList.getCode()) {
            throw new ServiceException(skuPriceList.getMsg());
        }
        List<SkuPrice> priceListData = skuPriceList.getData();
        Map<Long, BigDecimal> skuIdToSalePriceMap = priceListData.stream().
                collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        StringBuilder stringBuilder = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuIdToSalePriceMap.get(orderItem.getSkuId()))!=0){
                stringBuilder.append("["+orderItem.getSkuName()+"]商品价格有变动;");
            }
        }
        if (StringUtils.hasText(stringBuilder)) {
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException(stringBuilder.toString());
        }
        //检验库存锁定库存 TODO
        List<SkuLockVo> skuLockVoList = orderForm.getOrderItemList().stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            return skuLockVo;
        }).collect(Collectors.toList());
        R<String> checkAndLock = remoteProductService.
                checkAndLock(orderForm.getTradeNo(),skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL==checkAndLock.getCode()) {
            throw new ServiceException(checkAndLock.getMsg());
        }
        String data = checkAndLock.getData();
        if (StringUtils.hasText(data)){
            throw new ServiceException(data);
        }
        //保存订单(order_info\order_item\order_log)
        Long orderId=null;
        try {
            orderId=saveOrder(orderForm);
        } catch (Exception e) {
            //下单异常，解锁库存  TODO
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }
        //删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);
        //7.发送延迟消息。指定支付等待时间，如果不支付，消费者处理延迟消息就会自动取消订单，解锁库存。
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,MqConst.ROUTING_CANCEL_ORDER,
                String.valueOf(orderId),MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderId;
    }

    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();

        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();
    }

    @Transactional
    @Override
    public void processCloseOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (orderInfo!=null &&orderInfo.getOrderStatus().intValue()==0) {
            orderInfo.setOrderStatus(-1); //  -1 取消订单
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderInfo> eq = new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(eq);
        List<OrderItem> orderItemList = orderItemMapper.
                selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public void processPaySucess(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().
                eq(OrderInfo::getOrderNo, orderNo).
                select(OrderInfo::getId, OrderInfo::getOrderStatus));
        if (orderInfo.getOrderStatus().intValue()==0) {
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}